package cn.sf.util;

import cn.sf.config.AliyunConfig;
import cn.sf.pojo.FileUploadResult;
import com.aliyun.oss.OSS;
import com.aliyun.oss.model.ListObjectsRequest;
import com.aliyun.oss.model.OSSObject;
import com.aliyun.oss.model.OSSObjectSummary;
import com.aliyun.oss.model.ObjectListing;
import org.apache.commons.lang3.RandomUtils;
import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.*;
import java.util.List;

import org.springframework.web.multipart.MultipartFile;


/**
 * @author 上传文件帮助类
 */
@Component
public class FileUpload {
    /**
     * 允许上传的格式
     */
    private static final String[] IMAGE_TYPE = new String[]{".bmp", ".jpg",
            ".jpeg", ".gif", ".png", ".mp4"};
    @Resource
    private OSS ossClient;
    @Resource
    private AliyunConfig aliyunConfig;

    /**
     * @return FileUploadResult
     * @author 团子
     * @desc 文件上传到oss
     * @Param uploadFile
     */
    public FileUploadResult upload(MultipartFile uploadFile) {

        // 校验图片格式
        boolean isLegal = false;
        for (String type : IMAGE_TYPE) {
            if (StringUtils.endsWithIgnoreCase(uploadFile.getOriginalFilename(),
                    type)) {
                isLegal = true;
                break;
            }
        }
        //封装Result对象，并且将文件的byte数组放置到result对象中
        FileUploadResult fileUploadResult = new FileUploadResult();
        if (!isLegal) {
            fileUploadResult.setStatus("error");
            return fileUploadResult;
        }
        //文件新路径
        String fileName = uploadFile.getOriginalFilename();

        System.out.println(uploadFile.getOriginalFilename());
        String filePath = getFilePath(fileName);
        String filePath2=filePath+"?x-oss-process=video/snapshot,t_10000,m_fast,w_800,f_png";
        System.out.println("看看是不是2"+filePath);
        // 上传到阿里云
        try {
            ossClient.putObject(aliyunConfig.getBucketName(), filePath, new
                    ByteArrayInputStream(uploadFile.getBytes()));
        } catch (Exception e) {
            e.printStackTrace();
            //上传失败
            fileUploadResult.setStatus("error");
            return fileUploadResult;
        }
        fileUploadResult.setStatus("done");
        fileUploadResult.setResponse("success");
        fileUploadResult.setName(this.aliyunConfig.getUrlPrefix() + filePath);
        fileUploadResult.setUid(String.valueOf(System.currentTimeMillis()));


        return fileUploadResult;
    }

    /**
     * @author 团子
     * @desc 生成路径以及文件名 例如：//images/2019/08/10/15564277465972939.jpg
     * @date 2019-07-31 11:31
     */
    private String getFilePath(String sourceFileName) {
        System.out.println("这个文件的上传生成的路径:" + sourceFileName);
        String right = sourceFileName.substring(sourceFileName.indexOf(".") + 1);
        DateTime dateTime = new DateTime();
        String url = "";
        if (right.equals("mp4")) {
            url = "video/" + dateTime.toString("yyyy")
                    + "/" + dateTime.toString("MM") + "/"
                    //用户id用户信息 视频id                  用户id+信息
                    + dateTime.toString("dd") + "/" + System.currentTimeMillis() + RandomUtils.nextInt(100, 9999) + "." +
                    StringUtils.substringAfterLast(sourceFileName, ".");
        } else {
            url = "images/" + dateTime.toString("yyyy")
                    + "/" + dateTime.toString("MM") + "/"
                    //用户id用户信息 视频id                  用户id+信息
                    + dateTime.toString("dd") + "/" + System.currentTimeMillis() + RandomUtils.nextInt(100, 9999) + "." +
                    StringUtils.substringAfterLast(sourceFileName, ".");
        }

        System.err.println("url:" + url);
        return url;
    }

    /**
     * @author 团子
     * @desc 查看文件列表
     * @date 2019-07-31 11:31
     */
    public List<OSSObjectSummary> list() {
        // 设置最大个数。
        final int maxKeys = 200;
        // 列举文件。
        ObjectListing objectListing = ossClient.listObjects(new ListObjectsRequest(aliyunConfig.getBucketName()).withMaxKeys(maxKeys));

        List<OSSObjectSummary> sums = objectListing.getObjectSummaries();
        return sums;
    }

    /**
     * @return FileUploadResult
     * @desc 根据文件名删除oss上的文件
     * @author 团子
     * @Param objectName
     */
    public FileUploadResult delete(String objectName) {
        // 根据BucketName,objectName删除文件
        ossClient.deleteObject(aliyunConfig.getBucketName(), objectName);
        FileUploadResult fileUploadResult = new FileUploadResult();
        fileUploadResult.setName(objectName);
        fileUploadResult.setStatus("removed");
        fileUploadResult.setResponse("success");
        return fileUploadResult;
    }

    /**
     * @author 团子
     * @desc 下载文件
     * @date 2019-07-31 11:31
     */
    public void exportOssFile(OutputStream os, String objectName) throws IOException {
        // ossObject包含文件所在的存储空间名称、文件名称、文件元信息以及一个输入流。
        OSSObject ossObject = ossClient.getObject(aliyunConfig.getBucketName(), objectName);
        // 读取文件内容。
        BufferedInputStream in = new BufferedInputStream(ossObject.getObjectContent());
        BufferedOutputStream out = new BufferedOutputStream(os);
        byte[] buffer = new byte[1024];
        int lenght = 0;
        while ((lenght = in.read(buffer)) != -1) {
            out.write(buffer, 0, lenght);
        }
        if (out != null) {
            out.flush();
            out.close();
        }
        if (in != null) {
            in.close();
        }
    }
}
